package com.demo.ribbon.server.controller;

import com.demo.ribbon.server.domain.Hello;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/hello")
public class RibbonController {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    DiscoveryClient discoveryClient;

    private static Map<String, Hello> users = Maps.newConcurrentMap();

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public Hello addUser(@RequestParam(value = "name") String name, @RequestParam(value = "age") Integer age) {
        discoveryClient.getServices().forEach(id -> {
            discoveryClient.getInstances(id).forEach(instance -> {
                logger.info("/hello, host:" + instance.getHost() + ", service_id:" + instance.getServiceId());
            });
        });
        Hello hello = new Hello(name, age);
        users.put(name, hello);
        return hello;
    }
}
